<?php

namespace App\Http\Controllers\Customer\Api;

use App\Facades\WeChatService;
use App\Facades\WeChatDeviceService;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Utils\WechatSdk\XmlOperator;
use Illuminate\Http\Request;
use Input;

use Exception;

class WeChatController extends Controller{
    
    /**
     * 接口配置信息
     * @return [type] 
     */
    public function config(){
        // 获取到微信请求里包含的几项内容
        $signature = Input::get('signature');
        $timestamp = Input::get('timestamp');
        $nonce     = Input::get('nonce');
        
        $result = WeChatService::checkSignature($signature, $timestamp, $nonce);
        if($result){
            
            return Input::get('echostr');
        }
    }

    /**
     * 当普通微信用户向公众账号发消息时，微信服务器将POST消息的XML数据包到这个方法
     * @return [type] 
     */
    public function react(){
        // $message = Request::getContent();
        $message = file_get_contents('php://input');
        $message = XmlOperator::parseXml($message);
        return '';

        //关注、取消关注事件
        if($message['MsgType'] == 'event'){
            if($message['Event'] == 'subscribe'){
                // UserService::subscribe($message);
                // $data = [
                //             'ToUserName' => $message['FromUserName'],
                //             'FromUserName' => $message['ToUserName'],
                //             'CreateTime' => time(),
                //             'MsgType' => 'text',
                //             'Content' => '',
                //         ];
                // return XmlOperator::genXML($data);
                return '';
            }
            if($message['Event'] == 'unsubscribe'){
                // UserService::unsubscribe($message);
                return '';
            }
        }
        //普通消息
        if($message['MsgType'] == 'text'){
            
            return '';
        }
    }

    public function getWxConfig(Request $request)
    {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        return $jssdkSignPackage = WeChatService::getJssdkSignPackage($url);
    }

    /*
    测试用创建菜单
     */
    public function createMenu(Request $request){
        WeChatService::createMenu();
    }


}